package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void delete(Long id) {
        System.out.println(id);
        roleMapper.deleteRealation(id);
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Role role, Long[] ids) {
        roleMapper.insert(role);

        if (ids != null && ids.length > 0) {
            for (Long permissionId : ids) {
                roleMapper.insertRealation(role.getId(), permissionId);
            }
        }
    }

    @Override
    public Role selectOne(Long id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        return role;
    }

    @Override
    public List<Role> selectAll() {
        return roleMapper.selectAll();
    }


    @Override
    public void update(Role role, Long[] ids) {
        roleMapper.deleteRealation(role.getId());
        roleMapper.updateByPrimaryKey(role);
        if (ids != null && ids.length > 0) {
            for (Long permissionId : ids) {
                roleMapper.insertRealation(role.getId(), permissionId);
            }
        }
    }


    @Override
    public PageInfo<Role> query(QueryObject qo) {
        /*int count = roleMapper.selectForCount(qo);

        if(count == 0){
            PageResult<Role> pageResult = new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), 0, Collections.emptyList());
            return pageResult;
        }

        int totalPage = count%qo.getPageSize()== 0
                ? count/qo.getPageSize() : count/qo.getPageSize()+1;

        if(qo.getCurrentPage()>totalPage){
            qo.setCurrentPage(totalPage);
        }*/
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Role> roles = roleMapper.selectForList(qo);
        //return new PageResult(qo.getCurrentPage(),qo.getPageSize(),count,roles);
        return new PageInfo<Role>(roles);
    }

}
